import {ref, onMounted} from "vue";
import {
    CameraResultType,
    CameraSource,
    Plugins,
    CameraPhoto,
    FilesystemDirectory,
} from "@capacitor/core";
import axios from "axios";
/* eslint-disable */

const {Filesystem, Storage} = Plugins;

const convertBlobToBase64 = (blob: Blob) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onerror = reject;
        reader.onload = () => {
            resolve(reader.result);
        };
        reader.readAsDataURL(blob);
    });

const savePicture = async (
    photo: CameraPhoto,
    fileName: string
): Promise<Photo> => {
    let base64Data: string;
    // Fetch the photo, read as a blob, then convert to base64 format

    // Fetch the photo, read as a blob, then convert to base64 format
    const response = await fetch(photo.webPath!);
    const blob = await response.blob();
    base64Data = (await convertBlobToBase64(blob)) as string;

    const savedFile = await Filesystem.writeFile({
        path: fileName,
        data: base64Data,
        directory: FilesystemDirectory.Data,
    });

    // Use webPath to display the new image instead of base64 since it's
    // already loaded into memory
    return {
        filepath: fileName,
        webviewPath: photo.webPath,
    };
};
// @ts-ignore
const img2base64 = (img) => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    // @ts-ignore
    ctx.drawImage(img, 0, 0, img.width, img.height);
    // @ts-ignore
    const ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    return canvas.toDataURL("image/" + ext);
};

const postImg = (data) => {
    return axios.post("https://m.ctrip.com/restapi/soa2/21066/uploadMedia", {
        base64Str: data,
    });
};

export function usePhotoGallery() {
    const {Camera} = Plugins;
    const PHOTO_STORAGE = "photos";
    const photos = ref<Photo[]>([]);
    let predictions = ref<any>([])

    const cachePhotos = () => {
        Storage.set({
            key: PHOTO_STORAGE,
            value: JSON.stringify(photos.value),
        });
    };

    const loadSaved = async () => {
        const photoList = await Storage.get({key: PHOTO_STORAGE});
        const photosInStorage = photoList.value ? JSON.parse(photoList.value) : [];
        console.log(photosInStorage);

        // If running on the web...
        for (const photo of photosInStorage) {
            const file = await Filesystem.readFile({
                path: photo.filepath,
                directory: FilesystemDirectory.Data,
            });
            // Web platform only: Load the photo as base64 data
            photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
        }

        photos.value = photosInStorage;
    };

    const loadImage = (img) => {
        return new Promise((resolve, reject) => {
            img.onload = async () => {
                const base64 = await img2base64(img);
                resolve(base64)
            }
        })
    }

    onMounted(loadSaved);

    const takePhoto = async () => {
        const cameraPhoto = await Camera.getPhoto({
            resultType: CameraResultType.Uri,
            source: CameraSource.Camera,
            quality: 100,
        });

        const image = new Image();
        // @ts-ignore
        image.src = cameraPhoto.webPath;

        const base64 = await loadImage(image)

        const fileName = new Date().getTime() + ".jpeg";
        // const picPath = await savePicture(cameraPhoto, fileName);
        // const picData = await Filesystem.readFile({
        //     path: picPath.filepath,
        //     directory: FilesystemDirectory.Data,
        // });
        // const bytes = window.atob(arr[1]);
        // const ab = new ArrayBuffer(bytes.length);
        // const ia = new Uint8Array(ab);
        // for (var i = 0; i < bytes.length; i++) {
        //     ia[i] = bytes.charCodeAt(i);
        // }
        // const bob = new Blob([ab], {type: mime});

        const data = await postImg(base64);
        console.log(data);

        const galleryData = await axios.post(
            "https://southcentralus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/5c00375c-a1d6-4c88-b0f7-9e63cba607c3/classify/iterations/Iteration5/url",
            {Url: data.data.url},
            {
                headers: {
                    "Prediction-Key": "7fee05ce941445feab591cb78492afa0",
                    "Content-Type": "application/json",
                },
            }
        );
        console.log(galleryData);
        // @ts-ignore
        const savedFileImage = {
            filepath: fileName,
            webviewPath: cameraPhoto.webPath,
        };

        photos.value = [savedFileImage, ...photos.value];
        predictions.value = [...galleryData.data.predictions]

        console.log(predictions);
    };

    return {
        photos,
        takePhoto,
        predictions
    };
}

export interface Photo {
    filepath: string;
    webviewPath?: string;
}
